/**
 * 
 */
package com.juphoon.oauth.vaildate.code.impl;

import com.juphoon.oauth.core.properties.SecurityConstants;
import com.juphoon.oauth.core.vaildate.code.ValidateCode;
import com.juphoon.oauth.core.vaildate.code.ValidateCodeException;
import com.juphoon.oauth.core.vaildate.code.ValidateCodeRepository;
import com.juphoon.oauth.core.vaildate.code.ValidateCodeType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

/**
 * 基于redis的验证码存取器，避免由于没有session导致无法存取验证码的问题
 * 
 * @author zhailiang
 *
 */
@Component
@Slf4j
public class RedisValidateCodeRepository implements ValidateCodeRepository {

	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;


	@Override
	public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
		String key = buildKey(request, type);
		log.info(key);
		redisTemplate.opsForValue().set(buildKey(request, type), code, 30, TimeUnit.MINUTES);
	}


	@Override
	public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
		Object value = redisTemplate.opsForValue().get(buildKey(request, type));
		if (value == null) {
			return null;
		}
		return (ValidateCode) value;
	}


	@Override
	public void remove(ServletWebRequest request, ValidateCodeType type) {
		redisTemplate.delete(buildKey(request, type));
	}

	/**
	 * @param request
	 * @param type
	 * @return
	 */
	private String buildKey(ServletWebRequest request, ValidateCodeType type) {
		if (type == ValidateCodeType.IMAGE) {
			String deviceId = request.getParameter("deviceId");
			if (StringUtils.isBlank(deviceId)) {
				throw new ValidateCodeException("请在请求中携带deviceId参数");
			}
			return "code:" + type.toString().toLowerCase() + ":" + deviceId;
		} else if (type == ValidateCodeType.SMS) {
			String mobile = request.getParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE);

			if (StringUtils.isBlank(mobile)) {
				throw new ValidateCodeException("请在请求中携带mobile参数");
			}
			return "code:" + type.toString().toLowerCase() + ":" + mobile;
		}
		throw new ValidateCodeException("验证码url错误");
	}

}
